import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((1120, 768))
pygame.display.set_caption("ApplePy")
pygame.mouse.set_visible(True)

background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((0, 0, 0))

font = pygame.font.SysFont(None, 48)

def write_ch(ch, t, row, col):
    foreground_color = [(0, 0, 0), (255, 0, 0), (0, 0, 255), (0, 255, 0)][t]
    background_color = [(0, 255, 0), (128, 0, 0), (0, 0, 100), (0, 0, 0)][t]
    text = font.render(ch, True, foreground_color, background_color)
    background.blit(text, (col * 28, row * 32))
    screen.blit(background, (0, 0))
    pygame.display.flip()

def text(address, value):
    # map address to (x,y) and apple char to ASCII

    base = address - 0x0400
    row_offset = base // 0x80
    row_group = (base % 0x80) // 0x28 # 40-columns
    if row_group == 3:
        return # @@@
    row = row_offset + 8 * row_group
    column = (base % 0x80) % 40

    ch = chr(0x20 + ((value + 0x20) % 0x40))

    t = value >> 6

    write_ch(ch, t, row, column)

def check_keyboard(memory):
    for event in pygame.event.get():
        if event.type == QUIT:
            import sys; sys.exit(1)
        if event.type == KEYDOWN:
            memory[0xC000] = event.key | 0x80
